package com.tianji.aigc.memory;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.tianji.aigc.service.ChatService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Slf4j
public class RedisChatMemoryRepository implements ChatMemoryRepository {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String DEFAULT_PREFIX = "CHAT:";

    /**
     * 查询所有会话的对话id
     */
    @Override
    public List<String> findConversationIds() {
        Set<String> keys = stringRedisTemplate.keys(DEFAULT_PREFIX);
        return ListUtil.toList(keys);
    }

    /**
     * 根据对话Id获得会话内容
     */
    @Override
    public List<Message> findByConversationId(String conversationId) {
        String key = getKey(conversationId);
        var listOps = stringRedisTemplate.boundListOps(key);
        List<String> json = listOps.range(0, -1);
        if (json == null) {
            log.error("会话不存在：{}", key);
            return ListUtil.empty();
        }
        return CollStreamUtil.toList(json, MessageUtil::toMessage);
    }

        /**
     * 保存会话内容
     * @param conversationId 会话ID
     * @param messages 消息列表
     */
    @Override
    public void saveAll(String conversationId, List<Message> messages) {
        Assert.notEmpty(messages, "消息列表不能为空");
        String key = getKey(conversationId);
        var listOps = stringRedisTemplate.boundListOps(key);
        // 先删除原有会话数据
        deleteByConversationId(conversationId);
        // 将消息列表序列化后保存到Redis
        messages.forEach(message -> {
            listOps.rightPush(MessageUtil.toJson(message));
        });
    }


    /**
     * 删除会话内容
     */
    @Override
    public void deleteByConversationId(String conversationId) {
        stringRedisTemplate.delete(getKey(conversationId));
    }

    public String getKey(String conversationId) {
        return DEFAULT_PREFIX + conversationId;
    }
}
